package com.chenyh.backend;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import com.chenyh.backend.domain.WebUser;
import com.chenyh.backend.util.HibernateUtil;
import com.chenyh.backend.util.Md5Util;
import com.octo.captcha.service.CaptchaServiceException;

/**
 * Servlet implementation class TestUser
 */
public class TestUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestUser() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    private boolean checkAccess(HttpServletRequest request, HttpServletResponse response) throws IOException{
    	HttpSession session=request.getSession(false);
    	if(session==null || session.getAttribute("name")==null){
    		response.getWriter().println("Login first 登录");
    		return false;
    	}
		return true;
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().println("Unsupported method!");
		response.setContentType("text/html");
		if(!checkAccess(request, response)){
			return;
		}
		HttpSession client=request.getSession(true);
		response.getWriter().println("You are "+client.getAttribute("name")+"<br />");
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
        List<WebUser> result = session.createQuery("from WebUser").list();
        session.getTransaction().commit();
        for(WebUser wu : result){
        	response.getWriter().println(wu.getId()+" "+wu.getName()+" "+wu.getDate()+"<br />");
        } 
		response.flushBuffer();
	}
	
	private boolean checkCaptcha(HttpServletRequest request, HttpServletResponse response){
        //remenber that we need an id to validate!
        String captchaId = request.getSession().getId();
        //retrieve the response
        String resp = request.getParameter("j_captcha_response");
        boolean isResponseCorrect = false;
        // Call the Service method
         try {
             isResponseCorrect = CaptchaServiceSingleton.getInstance().validateResponseForID(captchaId,
            		 resp);
         } catch (CaptchaServiceException e) {
              //should not happen, may be thrown if the id is not valid
         }
         return isResponseCorrect;
	}
	
	private void do_reg(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.getWriter().println("reg"+" "+request.getParameter("name")+"<br />");
		String name = request.getParameter("name");
		if(!checkCaptcha(request, response)){
			response.getWriter().println("Captcha error!");
			return ;
		}
		
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        
        try{
        	session.beginTransaction();
        	List result = session.createQuery("from WebUser where name='"+name+"'").list();
       // session.getTransaction().commit();
	        if(result.size()!=0){
	        	response.flushBuffer();
	        	response.getWriter().println("ERROR: User exists");
	        	response.flushBuffer();
	        	return;
	        }
      
	        session.beginTransaction();
	        WebUser wu = new WebUser();
	        wu.setName(name);
	        wu.setPassword(Md5Util.encode(request.getParameter("pass")));
	        wu.setDate(new Date());
	        wu.setAge(Integer.parseInt(request.getParameter("age")));
	        session.save(wu);
	        session.getTransaction().commit();
        }catch(Exception e){
        	session.getTransaction().rollback();
        	response.getWriter().println("ERROR:"+e.getMessage());
        }finally{
        	//session.close();
        }
        response.getWriter().println("Done");
	}
	
	private void do_login(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String name = request.getParameter("name");
		String pass = Md5Util.encode(request.getParameter("pass"));
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();	
        try{
        	session.beginTransaction();
        	List<WebUser> result = session.createQuery("from WebUser where name='"+name+"' and password='"+pass+"'").list();
        	session.getTransaction().commit();
        	if(result.isEmpty()){
        		response.getWriter().println("Login Failed");
        	}else{
        		response.getWriter().println("Welcome ");
        		HttpSession client=request.getSession(true);
        		client.setAttribute("name", result.get(0).getName());
        	}
        
        }catch(Exception e){
        	response.getWriter().println("ERROR:"+e.getMessage());
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */ 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session=request.getSession(true);
		String type = request.getParameter("type");
		System.out.println(type);
		if("reg".equals(type)){
			do_reg(request, response);
		}else if("login".equals(type)){
			do_login(request,response);
		}

	}

}
